package xx.iverson.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * xx.iverson.util.WeatherUtil
 * 描述：获取天气工具类
 * on 2025/6/26-下午5:05
 *
 * @author weijx
 */
@Component
@Slf4j
public class WeatherUtil {
    private static String IP_API_URL;
    private static String IP_API_KEY;
    private static String WEATHER_API_URL;
    private static String WEATHER_API_KEY;

    @Value("${aggregated.ipApiKey}")
    private String ipApiKey;

    @Value("${aggregated.ipApiUrl}")
    private String ipApiUrl;

    @Value("${aggregated.weatherApiUrl}")
    private String weatherApiUrl;

    @Value("${aggregated.weatherApiKey}")
    private String weatherApiKey;

    /**
     * 获取ip
     *
     * @param request HttpServletRequest对象
     * @return IP地址信息
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                ip = "127.0.0.1";
            }
        }
        // 取第一个IP（防止多级代理）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        log.info("获取到ip为：{}",ip);
        return ip;
    }

    public static String getAddress(String ip) throws IOException {

        HashMap<String, String> map = new HashMap<>();
        map.put("key", IP_API_KEY);
        map.put("ip", ip);

        StringBuilder response = null;
        URL url = new URL(String.format("%s?%s", IP_API_URL, params(map)));
        BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
        String inputLine;
        response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String jsonString = response.toString();
        JSONObject jsonObj = JSON.parseObject(jsonString);
        JSONObject resultObj = jsonObj.getJSONObject("result");
        log.info("根据ip：{},获取到地址为：{}",ip,resultObj.getString("City"));
        return resultObj.getString("City");
    }

    public static String getWeather(String city) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        map.put("key", WEATHER_API_KEY);
        map.put("city", city);

        URL url = new URL(String.format("%s?%s", WEATHER_API_URL, params(map)));
        BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        log.info("根据地址：{},获取到天气为：{}",city, response);
        return String.valueOf(response);
    }

    /**
     * @param map 参数
     * @return String
     */
    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
                    } catch (Exception e) {
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }

    @PostConstruct
    public void init() {
        IP_API_URL = ipApiUrl;
        IP_API_KEY = ipApiKey;
        WEATHER_API_URL = weatherApiUrl;
        WEATHER_API_KEY = weatherApiKey;
    }
}
